package com.wjerp.tplus.server.common.security;

import com.wjerp.tplus.server.common.exception.BusinessException;
import com.wjerp.tplus.server.common.exception.UnAuthException;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author lishuailei
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private final Logger logger = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.header}")
    private String tokenHeader;

    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        final String requestHeader = request.getHeader(this.tokenHeader);

        String username = null;
        String authToken = null;
       
        Boolean flag=true;
        if (requestHeader != null && requestHeader.startsWith("Bearer ") && !requestHeader.substring(7).trim().equalsIgnoreCase("null")) {
            authToken = requestHeader.substring(7);
            try {
                username = jwtTokenUtil.getUsernameFromToken(authToken);
                //userDisplayId = jwtTokenUtil.getUserDisplayIdFromToken(authToken);
                //issuer = jwtTokenUtil.getIssuerFromToken(authToken);
            } catch (IllegalArgumentException e) {
                flag=false;
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
                logger.error("an error occured during getting username from token", e);
            } catch (BusinessException e){
                flag=false;
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
                logger.error(e.getErrorCode() + ": " + e.getErrorMsg(), e);
                //throw new UnAuthException();

            }
        } else {
            logger.warn("couldn't find bearer string, will ignore the header");
        }
        
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
        	logger.info("checking authentication for user " + username);
        	
            // It is not compelling necessary to load the use details from the database. You could also store the information
            // in the token and read it from it. It's up to you ;)
            //UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

            // For simple validation it is completely sufficient to just check the token integrity. You don't have to call
            // the database compellingly. Again it's up to you ;)
        	try{
	            if (jwtTokenUtil.validateToken(authToken)) {
	            	UserDetails userDetails = jwtTokenUtil.getUserInfoFromToken(authToken);
	            	
	                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
	                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
	                logger.info("authenticated user " + username + ", setting security context");
	                SecurityContextHolder.getContext().setAuthentication(authentication);
	            }
        	}catch(BusinessException e){
        		logger.error(e.getErrorCode()+ ": " + e.getErrorMsg(), e);
        	}
        }

        if(flag){
            chain.doFilter(request, response);
        }
    }
}